<?php

namespace Acme\FirmUsersBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Acme\FirmUsersBundle\Form\RegistrUser;

class SecurityController extends Controller {

  /**
   * @Route("/login", name="_security_login")
   * 
   */
  public function loginAction(\Symfony\Component\HttpFoundation\Request $request) {
    if ($this->get('request')->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
      $error = $this->get('request')->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    }
    else {
      $error = $this->get('request')->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
    }
    $session = $request->getSession();
    if ($error) {
      $session->setFlash('error', $error->getMessage());
    }
    return $this->redirect($session->get('referer', '/'));
//        return  array(
//            'last_username' => $this->get('request')->getSession()->get(SecurityContext::LAST_USERNAME),
//            'error' => $error
//        );
  }

  /**
   * @Route("/registr", name="_registr_form")
   * 
   */
  public function registrAction(\Symfony\Component\HttpFoundation\Request $request) {
    if ($request->get('user_type', 'client') == 'firm') {
     $form = $this->createForm(new \Acme\FirmUsersBundle\Form\RegistrFirmUser()); 
     return $this->registrUser($request, $form, 'ROLE_FIRM');
    }
    else {
      $form = $this->createForm(new \Acme\FirmUsersBundle\Form\RegistrClientUser());
      return $this->registrUser($request, $form, 'ROLE_CLIENT');
    }
  }

  protected function registrUser(\Symfony\Component\HttpFoundation\Request $request, $form, $role_string) {
    $session = $request->getSession();
    if ('POST' == $request->getMethod()) {
      $form->bindRequest($request);
      if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $role = $this->getDoctrine()->getRepository('AcmeFirmUsersBundle:Role')->findOneByName($role_string);
        $user = $form->getData();
        $user->getUserRoles()->add($role);
        $em->persist($user);
        $em->flush();
        $session->setFlash('notice', 'User Add');
      }
    }
    return $this->redirect($session->get('referer', '/'));
  }

  /**
   * @Route("/registr_widget", name="_registr_widget")
   * @Template()
   */
  public function registr_widgetAction(\Symfony\Component\HttpFoundation\Request $request) {
    $form = $this->createForm(new \Acme\FirmUsersBundle\Form\RegistrUser());
    $session = $request->getSession();
    $session->set('referer', $request->getRequestUri());
    return array(
        'last_username' => $this->get('request')->getSession()->get(SecurityContext::LAST_USERNAME),
        'form' => $form->createView()
    );
  }

  /**
   * @Secure(roles="IS_AUTHENTICATED_FULLY")
   * @Route("/user_page", name="_user_page")
   * @Template()
   */
  public function user_pageAction(\Symfony\Component\HttpFoundation\Request $request) {
    $user = $this->get('security.context')->getToken()->getUser();
    $session = $request->getSession();
    $form = $this->createForm(new \Acme\FirmUsersBundle\Form\EditUserForm(), $user);
    if ('POST' == $request->getMethod()) {
      $form->bindRequest($request);
      if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $form->getData();
        $em->flush();
        $session->setFlash('notice', 'Данные обновлены');
      }
    }
    return array('form' => $form->createView());
  }

  /**
   * @Secure(roles="ROLE_FIRM")
   * @Route("/firm_page", name="_firm_page")
   * @Template()
   */
  public function firm_pageAction(\Symfony\Component\HttpFoundation\Request $request) {
    $user = $this->get('security.context')->getToken()->getUser();
    $session = $request->getSession();
    $firm = $this->getDoctrine()->getRepository('AcmeFirmsBundle:Firms')->findOneByUser($user->getId());
    if (!$firm) {
      $firm = new \Acme\FirmsBundle\Entity\Firms();
    }
    $form = $this->createForm(new \Acme\FirmsBundle\Form\FirmsType(), $firm);
    if ('POST' == $request->getMethod()) {
      $form->bindRequest($request);
      if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $firm = $form->getData();

        if (!$firm->getId()) {
          $firm->setUser($user);
          $em->persist($firm);
        }
        $em->flush();
        $session->setFlash('notice', 'Данные обновлены');
      }
    }
    $jqGrid = new \Alex616\jqGridBundle\lib\jqGridObject();
      $jqGrid->setProperty('url', $this->generateUrl('_get_staffs', array('firm_id' => $firm->getId())))
             ->setProperty('datatype', 'json')
             ->startBlock('colNames')
              ->setProperty(null, 'Id')
              ->setProperty(null, 'Название')
              ->setProperty(null, 'Категория')
             ->endBlock()
             ->startBlock('colModel')
              ->startBlock()
                ->setProperty('name', 'id')
                ->setProperty('index', 'id')
                ->setProperty('width', 55)
                ->setProperty('editable', false)
                ->startBlock('editoptions')
                  ->setProperty('readonly', true)
                  ->setProperty('size', 10)
                ->endBlock()
              ->endBlock()
              ->startBlock()
                ->setProperty('name', 'name')
                ->setProperty('index', 'name')
                ->setProperty('width', 150)
                ->setProperty('editable', true)
                ->startBlock('editoptions')
                  ->setProperty('size', 25)
                ->endBlock()
              ->endBlock()
              ->startBlock()
                ->setProperty('name', 'note')
                ->setProperty('index', 'note')
                ->setProperty('width', 200)
                ->setProperty('sortable', false)
                ->setProperty('editable', true)
                ->startBlock('editoptions')
                  ->setProperty('size', 25)
                ->endBlock()
              ->endBlock()
             ->endBlock()
             ->setProperty('rowNum', 10)
             ->startBlock('rowList')
              ->setProperty(null, 10)
              ->setProperty(null, 20)
              ->setProperty(null, 30)
             ->endBlock()
              ->setProperty('pager', '#pager2')
              ->setProperty('sortname', 'id')
              ->setProperty('viewrecords', true)
              ->setProperty('sortorder', 'asc')
              ->setProperty('multiselect', true)
              ->setProperty('caption', 'Товары')
              ->setProperty('editurl', $this->generateUrl('_del_staff'))
              ->setProperty('height', 210)             
             ;
    return array('form' => $form->createView(), 'firm_id' => $firm->getId(), 'params' => $jqGrid->getProperties());
  }

}